package logic

import (
	"context"
	postApi "mldong/api/post"
	dao "mldong/internal/modules/sys/dao"
	"mldong/internal/modules/sys/entity"
	service "mldong/internal/modules/sys/service"
	"mldong/utility"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/jinzhu/copier"
)

func init() {
	// 注册服务实现
	utility.Register(service.PostServiceType, NewPostLogic())
}

type PostLogic struct {
	postDao *dao.PostDao
}

// 保存岗位接口实现
func (logic *PostLogic) Save(ctx context.Context, req *postApi.SaveReq) (res bool, err error) {
	unique := utility.CheckUnique(logic.postDao.Model(nil), "code", req.Code, nil, "唯一编码已存在，请检查code参数")
	if unique != nil {
		return false, unique
	}
	var post = entity.Post{}
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		req.ID = nil
		// 将req对象赋值给post
		copier.Copy(&post, &req)
		// 插入sys_post表
		post, err = logic.postDao.Insert(post, tx)
		if err != nil {
			return err
		}
		return nil
	})
	return post.ID != nil, err
}

// 修改岗位接口实现
func (logic *PostLogic) Update(ctx context.Context, req *postApi.UpdateReq) (res bool, err error) {
	unique := utility.CheckUnique(logic.postDao.Model(nil), "code", req.Code, req.ID, "唯一编码已存在，请检查code参数")
	if unique != nil {
		return false, unique
	}
	var post = entity.Post{}
	// 将req对象赋值给post
	copier.Copy(&post, &req)
	var count int64
	count, err = logic.postDao.UpdateById(post, nil)
	if err != nil {
		return false, err
	}
	return count > 0, err
}

// 删除岗位接口实现
func (logic *PostLogic) Remove(ctx context.Context, ids []string) (res bool, _ error) {
	// 遍历ids
	// for _, id := range ids {
	// 	logic.postDao.DeleteById(id)
	// }
	var count, err = logic.postDao.DeleteByIds(ids)
	if err != nil {
		return false, err
	}
	if count == 0 {
		return false, err
	}
	return true, err
}

// 根据ID获取岗位信息
func (logic *PostLogic) Detail(ctx context.Context, id string) (res postApi.PostVO, err error) {
	var postVO = postApi.PostVO{}
	var post entity.Post
	post, err = logic.postDao.GetById(id)

	// 将post对象赋值给postVO
	copier.Copy(&postVO, &post)

	return postVO, err
}

// 分页查询岗位接口实现
func (logic *PostLogic) Page(ctx context.Context, req *postApi.PageReq) (res postApi.PostPageVO, err error) {
	// 处理分页参数nil值
	utility.HandlePageParam(&req.PageParam)
	posts, total, err := logic.postDao.Page(*req.PageNum, *req.PageSize, func(model *gdb.Model) *gdb.Model {
		return utility.BuildQuery(req.PageParam, model)
	})
	var postVOS = []postApi.PostVO{}
	copier.Copy(&postVOS, &posts)
	postPage := postApi.PostPageVO{
		Rows: postVOS,
	}
	postPage.PageNum = *req.PageNum
	postPage.PageSize = *req.PageSize
	postPage.RecordCount = total
	// 计算 TotalPage
	if *req.PageSize > 0 {
		postPage.TotalPage = (total + *req.PageSize - 1) / *req.PageSize
	} else {
		postPage.TotalPage = 0 // 如果 PageSize 为 0，则 TotalPage 为 0
	}
	return postPage, err
}
func NewPostLogic() service.IPostService {
	return &PostLogic{
		postDao: dao.NewPostDao(),
	}
}
